package com.intelligentpension.bleconnect

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.*
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.hjq.toast.ToastUtils
import java.nio.charset.Charset
import java.util.*

class LowpowerActivity : AppCompatActivity() {

    private var tx: BluetoothGattCharacteristic? = null
    private var rx: BluetoothGattCharacteristic? = null
    var UART_UUID: UUID = UUID.fromString("0000FFE0-0000-1000-8000-00805F9B34FB")
    var TX_UUID: UUID = UUID.fromString("0000FFE1-0000-1000-8000-00805F9B34FB")
    var RX_UUID: UUID = UUID.fromString("0000FFE1-0000-1000-8000-00805F9B34FB")
    private lateinit var mMessage: TextView



    var SERVICE_SEND: UUID = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb")//系统内置可写(源码默认)
    var SERVICE_READ: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")//系统内置可读(源码默认)
    var SERVICE_READ_UUID: String ="00002902-0000-1000-8000-00805f9b34fb"//系统内置可读(源码默认)
    private var callBack = object : BluetoothGattCallback() {
        //TODO:监听连接状态的改变
        @SuppressLint("MissingPermission")
        override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
            super.onConnectionStateChange(gatt, status, newState)
            when (newState) {
                BluetoothGatt.STATE_CONNECTING -> {
                    ToastUtils.show("低功耗蓝牙正在连接")
                }
                BluetoothGatt.STATE_CONNECTED -> {
                    //00ToastUtils.show("低功耗蓝牙已经连接")
                    // TODO:启动发现服务
                    if (gatt != null) {
                        if (!gatt.discoverServices()) {//TODO:只有启动discoverServices方法后才能调用onServicesDiscovered方法

                            ToastUtils.show("启动寻找服务")
                        }
                    }
                }
                BluetoothGatt.STATE_DISCONNECTED -> {
                    ToastUtils.show("低功耗蓝牙已断开")
                }
            }
        }

        //TODO:启动服务被发现后,开始被调用
        @SuppressLint("MissingPermission")
        override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
            super.onServicesDiscovered(gatt, status)
            println("当前UUID${UART_UUID.toString()}")
            println("当前UUID${UART_UUID.toString()}")
            if (gatt?.getService(UART_UUID) == null) {
                ToastUtils.show("开启启动服务失败")
                gatt?.discoverServices()
                return
            }

            tx = gatt.getService(UART_UUID).getCharacteristic(TX_UUID)
            rx = gatt.getService(UART_UUID).getCharacteristic(RX_UUID)
            //TODO:获取指定的特征值
            if (tx != null) {
                var charaProp: Int = tx!!.properties

                //TODO:可读
                if (charaProp and BluetoothGattCharacteristic.PROPERTY_READ > 0) {

                }

                // TODO:可写，注：要 & 其可写的两个属性
                if (charaProp and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE > 0 || charaProp and BluetoothGattCharacteristic.PROPERTY_WRITE > 0) {

                }

                //  TODO:可通知，可指示
                if (charaProp and BluetoothGattCharacteristic.PROPERTY_NOTIFY > 0 || charaProp and BluetoothGattCharacteristic.PROPERTY_INDICATE > 0) {

                }
            }

            //TODO:更新RX特性,以启用通知(变成系统默认的)
            if (rx?.getDescriptor(SERVICE_READ) != null) {
                var desc: BluetoothGattDescriptor? = rx?.getDescriptor(SERVICE_READ)
                desc?.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE

                gatt.writeDescriptor(desc)

            }

            //TODO:直接设置通知,之后开始调用onCharacteristicChanged()方法
            if (!gatt.setCharacteristicNotification(rx, true)) {
                ToastUtils.show("不能设置rx特征")
            }



// B站视频上讲的是这个方法
//            if (gatt==null) return
//            var services = gatt.services
//            //TODO:获取所有的发现的服务
//            for (service in services.iterator()){
//                var characteristics = service.characteristics
//
//                //TODO:获取每个服务的所有特征
//                 for (characteristic in characteristics.iterator()){
//                     println("里面的UUID是"+characteristic.uuid.toString().trim()+"======"+SERVICE_SEND.toString().lowercase())
//                     if (characteristic.uuid.toString().lowercase() == SERVICE_READ_UUID){
//                         //TODO:设置特征通知
//                         gatt.setCharacteristicNotification(characteristic,true)
//
//                     }
//                 }
//            }


        }

        //TODO:连接服务后.开始调用onCharacteristicChanged()方法 ,这是BLE蓝牙发送的数据
        override fun onCharacteristicChanged(
            gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?
        ) {
            super.onCharacteristicChanged(gatt, characteristic)
            var value = characteristic?.value
            var msg = value?.let { String(it, 0, value.size, Charset.forName("GBK")) }
            runOnUiThread {
                mMessage.append(msg)
            }
        }

        override fun onReadRemoteRssi(gatt: BluetoothGatt?, rssi: Int, status: Int) {
            super.onReadRemoteRssi(gatt, rssi, status)
        }
    }


    private lateinit var mMessageSend: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lowpower)
        mMessage = findViewById<TextView>(R.id.messageText)

        var devices: BluetoothDevice? =
            intent.getParcelableExtra<BluetoothDevice>(ContectUtils.EXTRAS_DEVICEST) ?: return

        //TODO:低功耗蓝牙的连接来了
        // 只有sdk大于30的时候,才会需要这个权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(
                    this, Manifest.permission.BLUETOOTH_CONNECT
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
        }
        var connectGatt = devices?.connectGatt(this, false, callBack)

       mMessageSend= findViewById<EditText>(R.id.message_send)
        findViewById<Button>(R.id.send).setOnClickListener {
            var data = mMessageSend.text.toString()
            if (data.isEmpty()){
                ToastUtils.show("请输入数字")
                return@setOnClickListener
            }


            if (connectGatt!=null && connectGatt.connect()){

                //必须用二进制发送的GBK发送
                var send = data.toByteArray(charset("GBK"))
                //特征设值
                tx!!.value =send
                connectGatt.writeCharacteristic(tx)
            }
        }
    }
}